#include "shmem.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "MQTTClient.h"
#include "cJSON.h"
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>
#include <signal.h>
#include <time.h>
#include <pthread.h>
#include <sqlite3.h>
#include "msg_queue_peer.h"

// 数据类型定义
typedef enum
{
    TYPE_BOOL = 1,
    TYPE_INT = 2,
    TYPE_FLOAT = 3
} DataType;

// STM32设备点表项
typedef struct
{
    uint16_t key;
    char name[32];
    DataType type;
    uint8_t status;
    union
    {
        int int_value;
        float float_value;
        int bool_value;
    } value;
} STM32Item;

// Modbus设备点表项
typedef struct
{
    uint16_t key;
    char name[32];
    uint16_t addr;
    DataType type;
    uint8_t status;
    union
    {
        int int_value;
        float float_value;
        int bool_value;
    } value;
} ModbusItem;

// 完整配置结构体
typedef struct
{
    int stm32_count;
    STM32Item stm32_items[100];
    int modbus_count;
    ModbusItem modbus_items[100];
    char version[10];
    struct
    {
        int type;   // 上报类型(0=不上报,1=定时上报,2=变化上报,3=刷新上报)
        int period; // 上报周期(秒)
    } report;
    struct
    {
        char addr[20];
        int port;
    } mqtt_server;
    struct
    {
        char addr[20];
        int port;
    } mb_dev;
    struct
    {
        char addr[20];
        int port;
    } mb_app;
} ConfigData;

typedef struct
{
    char action[20];    // 操作类型（"get_timestamp"或"get_data"）
    char timestamp[30]; // 时间戳
    char data[4096];    // 数据内容（JSON格式，增大缓冲区）
    int error_code;     // 错误码（0=成功，非0=失败）
    char error_msg[50]; // 错误信息
} QueryResponse;

// 消息队列结构体
struct msgbuf
{
    long mtype;
    int key;
    int value;
};
struct msgbuf send;

#define SHARED_MEM_NAME "point_table_shm"
#define SEM_NAME "/point_table_shm_sem"
#define MQTT_SERVER "tcp://192.168.51.19:1883" // 修改为你的MQTT服务器地址
#define CLIENT_ID "SensorClient"
#define TOPIC_UP "/qt-client/data/up"
#define TOPIC_DOWN "/qt-client/data/down"
#define QOS 1
#define TIMEOUT 10000L
#define MAGIC_ID 'A' // 共享内存键值生成标识
#define DB_PATH "database.db"
#define TABLE_NAME "data_records"
#define SQLITE_THREAD_INTERVAL 180 // 3分钟间隔（秒）

volatile int running = 1;
MQTTClient client;
sem_t *shm_sem;
ConfigData last_config = {0};
int first_run = 1;
int remote_refresh = 0;
sqlite3 *db;
pthread_t sqlite_thread;
pthread_t message_thread;
int sqlite_query_flag = 0;
char *sqlite_timestamp = NULL;
char *payload = NULL;

// 全局共享内存参数
struct shm_param shm; // 与shmem.h中定义保持一致

// 连接丢失回调
void connlost(void *context, char *cause)
{
    printf("\nConnection lost: %s\n", cause ? cause : "unknown reason");
    printf("Reconnecting to MQTT server...\n");

    int rc;
    MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
    opts.keepAliveInterval = 60;
    opts.cleansession = 0; // 使用持久会话，保留订阅信息

    while ((rc = MQTTClient_connect(client, &opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Reconnect failed, return code %d. Retrying in 5 seconds...\n", rc);
        sleep(5);
    }

    printf("Reconnected successfully. Resubscribing to topic: %s\n", TOPIC_DOWN);
    if (MQTTClient_subscribe(client, TOPIC_DOWN, QOS) != MQTTCLIENT_SUCCESS)
    {
        fprintf(stderr, "Failed to resubscribe to topic: %s\n", TOPIC_DOWN);
    }
}

// 解析MQTT命令
void parse_command(const char *json_str, ConfigData *config)
{
    cJSON *root = cJSON_Parse(json_str);
    if (!root)
    {
        printf("JSON解析失败: %s\n", json_str);
        return;
    }

    printf("解析命令: %s\n", json_str);

    // 更新上报类型
    cJSON *type = cJSON_GetObjectItem(root, "report_type");
    if (type && cJSON_IsNumber(type))
    {
        sem_wait(shm_sem);
        config->report.type = type->valueint;
        sem_post(shm_sem);
        printf("更新上报类型: %d\n", type->valueint);
    }

    // 更新上报周期
    cJSON *period = cJSON_GetObjectItem(root, "report_period");
    if (period && cJSON_IsNumber(period))
    {
        sem_wait(shm_sem);
        config->report.period = period->valueint;
        sem_post(shm_sem);
        printf("更新上报周期: %d秒\n", period->valueint);
    }

    // 处理刷新命令
    cJSON *refresh = cJSON_GetObjectItem(root, "report");
    if (refresh && cJSON_IsNumber(refresh) && refresh->valueint == 1)
    {
        remote_refresh = 1;
        printf("收到刷新命令\n");
    }

    // 处理SQLite命令
    cJSON *sqlite_cmd = cJSON_GetObjectItem(root, "sqlite3");
    if (sqlite_cmd && cJSON_IsNumber(sqlite_cmd))
    {
        int cmd_value = sqlite_cmd->valueint;
        printf("收到SQLite命令: %d\n", cmd_value);

        sem_wait(shm_sem);
        sqlite_query_flag = cmd_value;

        // 清除之前的时间戳
        if (sqlite_timestamp)
        {
            free(sqlite_timestamp);
            sqlite_timestamp = NULL;
        }

        // 获取时间戳参数
        cJSON *ts_param = cJSON_GetObjectItem(root, "timestamp");
        if (ts_param && cJSON_IsString(ts_param))
        {
            sqlite_timestamp = strdup(ts_param->valuestring);
            printf("SQLite时间戳参数: %s\n", sqlite_timestamp);
        }

        printf("设置sqlite_query_flag: %d\n", sqlite_query_flag);
        sem_post(shm_sem);
    }

    cJSON_Delete(root);
}

// MQTT消息回调
int message_arrived(void *context, char *topic, int len, MQTTClient_message *msg)
{
    ConfigData *config = (ConfigData *)context;
    char *payload = malloc(msg->payloadlen + 1);
    if (!payload)
        return 1;

    memcpy(payload, msg->payload, msg->payloadlen);
    payload[msg->payloadlen] = '\0';
    printf("消息到达主题: %s\n载荷: %s\n", topic, payload);

    // 解析消息类型并处理类型5的消息
    cJSON *root = cJSON_Parse(payload);
    if (root)
    {
        cJSON *type_json = cJSON_GetObjectItem(root, "type");
        if (type_json && cJSON_IsNumber(type_json) && type_json->valueint == 5)
        {
            // 处理类型5的消息队列数据
            cJSON *data = cJSON_GetObjectItem(root, "data");
            if (data && cJSON_IsObject(data))
            {
                // 提取key和value
                cJSON *key_json = cJSON_GetObjectItem(data, "key");
                cJSON *value_json = cJSON_GetObjectItem(data, "value");

                if (key_json && cJSON_IsNumber(key_json) && value_json)
                {
                    // 填充消息队列结构体
                    struct msgbuf send;
                    send.mtype = 1;
                    send.key = key_json->valueint;

                    // 处理value（可能是数字或字符串）
                    if (cJSON_IsNumber(value_json))
                    {
                        send.value = value_json->valueint;
                    }
                    else if (cJSON_IsString(value_json))
                    {
                        send.value = atoi(value_json->valuestring);
                    }
                    else
                    {
                        printf("无效的value格式\n");
                        cJSON_Delete(root);
                        free(payload);
                        return 1;
                    }

                    // 发送到对应的消息队列
                    if (send.key /100 == 2)
                    {
                        printf("ready to send to modbus: key=%d, value=%d\n", send.key, send.value);
                        if (msg_queue_send("modbus", &send, sizeof(send), 0) < 0)
                        {
                            printf("msg_queue_send error\n");
                        }
                    }
                    else if (send.key /100 == 1)
                    {
                        printf("ready to send to stm32: key=%d, value=%d\n", send.key, send.value);
                        if (msg_queue_send("stm32", &send, sizeof(send), 0) < 0)
                        {
                            printf("msg_queue_send error\n");
                        }
                    }
                    else
                    {
                        printf("key error: %d\n", send.key);
                    }
                }
                else
                {
                    printf("无效的key或value格式\n");
                }
            }
            else
            {
                printf("无效的data格式\n");
            }
        }
        cJSON_Delete(root);
    }
    else
    {
        printf("JSON解析失败\n");
    }

    // 处理其他命令
    parse_command(payload, config);
    free(payload);
    return 1;
}
// 创建JSON数据
char *create_json(ConfigData *config)
{
    cJSON *root = cJSON_CreateObject();
    cJSON *stm32_arr = cJSON_CreateArray();
    cJSON *modbus_arr = cJSON_CreateArray();

    cJSON_AddStringToObject(root, "version", config->version);
    cJSON_AddNumberToObject(root, "report_type", config->report.type);
    cJSON_AddNumberToObject(root, "report_period", config->report.period);

    // 添加STM32设备数据
    for (int i = 0; i < config->stm32_count && i < 100; i++)
    {
        STM32Item *item = &config->stm32_items[i];
        cJSON *obj = cJSON_CreateObject();

        cJSON_AddNumberToObject(obj, "key", item->key);
        cJSON_AddStringToObject(obj, "name", item->name);
        cJSON_AddNumberToObject(obj, "type", item->type);
        cJSON_AddNumberToObject(obj, "status", item->status);

        switch (item->type)
        {
        case TYPE_BOOL:
            cJSON_AddNumberToObject(obj, "value", item->value.bool_value);
            break;
        case TYPE_INT:
            cJSON_AddNumberToObject(obj, "value", item->value.int_value);
            break;
        case TYPE_FLOAT:
            cJSON_AddNumberToObject(obj, "value", item->value.float_value);
            break;
        default:
            cJSON_AddNullToObject(obj, "value");
        }

        cJSON_AddItemToArray(stm32_arr, obj);
    }
    cJSON_AddItemToObject(root, "stm32", stm32_arr);

    // 添加Modbus设备数据
    for (int i = 0; i < config->modbus_count && i < 100; i++)
    {
        ModbusItem *item = &config->modbus_items[i];
        cJSON *obj = cJSON_CreateObject();

        cJSON_AddNumberToObject(obj, "key", item->key);
        cJSON_AddStringToObject(obj, "name", item->name);
        cJSON_AddNumberToObject(obj, "addr", item->addr);
        cJSON_AddNumberToObject(obj, "type", item->type);
        cJSON_AddNumberToObject(obj, "status", item->status);

        switch (item->type)
        {
        case TYPE_BOOL:
            cJSON_AddNumberToObject(obj, "value", item->value.bool_value);
            break;
        case TYPE_INT:
            cJSON_AddNumberToObject(obj, "value", item->value.int_value);
            break;
        case TYPE_FLOAT:
            cJSON_AddNumberToObject(obj, "value", item->value.float_value);
            break;
        default:
            cJSON_AddNullToObject(obj, "value");
        }

        cJSON_AddItemToArray(modbus_arr, obj);
    }
    cJSON_AddItemToObject(root, "modbus", modbus_arr);

    char *json_str = cJSON_Print(root);
    cJSON_Delete(root);
    return json_str;
}

// 比较配置变化
int has_config_changed(ConfigData *curr, ConfigData *last)
{
    if (curr->report.type != last->report.type ||
        curr->report.period != last->report.period ||
        curr->stm32_count != last->stm32_count ||
        curr->modbus_count != last->modbus_count ||
        strcmp(curr->version, last->version) != 0)
    {
        return 1;
    }

    // 比较STM32点表
    for (int i = 0; i < curr->stm32_count; i++)
    {
        STM32Item *c = &curr->stm32_items[i];
        STM32Item *l = &last->stm32_items[i];

        if (c->key != l->key ||
            strcmp(c->name, l->name) != 0 ||
            c->type != l->type ||
            c->status != l->status ||
            (c->type == TYPE_BOOL && c->value.bool_value != l->value.bool_value) ||
            (c->type == TYPE_INT && c->value.int_value != l->value.int_value) ||
            (c->type == TYPE_FLOAT && c->value.float_value != l->value.float_value))
        {
            return 1;
        }
    }

    // 比较Modbus点表
    for (int i = 0; i < curr->modbus_count; i++)
    {
        ModbusItem *c = &curr->modbus_items[i];
        ModbusItem *l = &last->modbus_items[i];

        if (c->key != l->key ||
            strcmp(c->name, l->name) != 0 ||
            c->addr != l->addr ||
            c->type != l->type ||
            c->status != l->status ||
            (c->type == TYPE_BOOL && c->value.bool_value != l->value.bool_value) ||
            (c->type == TYPE_INT && c->value.int_value != l->value.int_value) ||
            (c->type == TYPE_FLOAT && c->value.float_value != l->value.float_value))
        {
            return 1;
        }
    }

    return 0;
}

// 复制配置
void copy_config(ConfigData *src, ConfigData *dst)
{
    memcpy(dst, src, sizeof(ConfigData));
}

// 发布数据
void publish_data(ConfigData *config)
{
    char *json = create_json(config);
    if (!json)
    {
        printf("创建JSON数据失败\n");
        return;
    }

    MQTTClient_message msg = MQTTClient_message_initializer;
    msg.payload = json;
    msg.payloadlen = strlen(json);
    msg.qos = QOS;
    msg.retained = 0;

    MQTTClient_deliveryToken token;
    int rc = MQTTClient_publishMessage(client, TOPIC_UP, &msg, &token);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        printf("发布消息失败, 返回代码 %d\n", rc);
    }
    else
    {
        MQTTClient_waitForCompletion(client, token, TIMEOUT);
        printf("消息发布成功\n");
    }

    free(json);
}

// 信号处理
void sig_handler(int signo)
{
    if (signo == SIGINT || signo == SIGTERM)
    {
        printf("\n捕获信号 %d, 正在清理...\n", signo);
        running = 0;

        // 断开MQTT连接
        if (MQTTClient_isConnected(client))
        {
            MQTTClient_disconnect(client, 1000);
        }
        MQTTClient_destroy(&client);

        // 关闭信号量
        sem_close(shm_sem);

        // 解除共享内存映射
        shm_detach(&shm);

        // 关闭数据库
        if (db)
        {
            sqlite3_close(db);
        }
        if (sqlite_timestamp)
        {
            free(sqlite_timestamp);
        }

        printf("正在退出...\n");
    }
}

// MQTT初始化
int mqtt_init()
{
    MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
    int rc;

    if (MQTTClient_create(&client, MQTT_SERVER, CLIENT_ID,
                          MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        fprintf(stderr, "创建MQTT客户端失败\n");
        return -1;
    }

    // 设置MQTT消息回调（在连接前设置）
    ConfigData *config = (ConfigData *)shm_getaddr(&shm);
    MQTTClient_setCallbacks(client, config, connlost, message_arrived, NULL);

    // 配置连接选项
    opts.keepAliveInterval = 60;
    opts.cleansession = 0; // 使用持久会话，保留订阅信息

    // 连接到MQTT服务器
    if ((rc = MQTTClient_connect(client, &opts)) != MQTTCLIENT_SUCCESS)
    {
        fprintf(stderr, "MQTT连接失败: %d\n", rc);
        MQTTClient_destroy(&client);
        return -1;
    }

    printf("已连接到MQTT服务器: %s\n", MQTT_SERVER);

    // 订阅下行主题
    if ((rc = MQTTClient_subscribe(client, TOPIC_DOWN, QOS)) != MQTTCLIENT_SUCCESS)
    {
        fprintf(stderr, "订阅主题失败: %s\n", TOPIC_DOWN);
        return -1;
    }
    printf("已订阅主题: %s\n", TOPIC_DOWN);

    return 0;
}

// 数据库初始化
int init_database()
{
    if (sqlite3_open(DB_PATH, &db) != SQLITE_OK)
    {
        fprintf(stderr, "打开数据库失败: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    printf("数据库连接成功: %s\n", DB_PATH);

    const char *sql = "CREATE TABLE IF NOT EXISTS data_records ("
                      "timestamp TEXT PRIMARY KEY, "
                      "data JSON NOT NULL);";
    char *errmsg;
    if (sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
    {
        fprintf(stderr, "创建表失败: %s\n", errmsg);
        sqlite3_free(errmsg);
        sqlite3_close(db);
        return -1;
    }

    printf("数据表检查/创建成功\n");
    return 0;
}

// 数据库插入线程函数
void *database_thread_func(void *arg)
{
    ConfigData *config = (ConfigData *)arg;
    char timestamp[30], *json_data;

    printf("数据库记录线程已启动，间隔: %d秒\n", SQLITE_THREAD_INTERVAL);

    while (running)
    {
        sem_wait(shm_sem);

        time_t now = time(NULL);
        strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", localtime(&now));

        json_data = create_json(config);
        if (json_data)
        {
            sqlite3_stmt *stmt;
            const char *sql = "INSERT OR REPLACE INTO data_records (timestamp, data) VALUES (?, ?)";

            if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK)
            {
                sqlite3_bind_text(stmt, 1, timestamp, -1, SQLITE_STATIC);
                sqlite3_bind_text(stmt, 2, json_data, -1, SQLITE_STATIC);

                if (sqlite3_step(stmt) != SQLITE_DONE)
                {
                    fprintf(stderr, "SQL执行失败: %s\n", sqlite3_errmsg(db));
                }
                else
                {
                    printf("数据库插入成功: %s\n", timestamp);
                }

                sqlite3_finalize(stmt);
            }
            else
            {
                fprintf(stderr, "SQL准备失败: %s\n", sqlite3_errmsg(db));
            }

            free(json_data);
        }

        sem_post(shm_sem);
        sleep(SQLITE_THREAD_INTERVAL); // 每3分钟执行一次
    }

    printf("数据库记录线程已停止\n");
    return NULL;
}

// 查询指定时间戳的数据
char *query_data_by_timestamp(const char *timestamp)
{
    if (!timestamp)
    {
        printf("query_data_by_timestamp: 时间戳为空\n");
        return NULL;
    }

    sqlite3_stmt *stmt;
    const char *sql = "SELECT data FROM data_records WHERE timestamp = ?";
    char *result = NULL;

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK)
    {
        sqlite3_bind_text(stmt, 1, timestamp, -1, SQLITE_STATIC);

        int rc = sqlite3_step(stmt);
        if (rc == SQLITE_ROW)
        {
            const char *data = (const char *)sqlite3_column_text(stmt, 0);
            if (data)
            {
                result = strdup(data);
                printf("查询成功: %s\n", timestamp);
            }
            else
            {
                printf("查询结果为空: %s\n", timestamp);
            }
        }
        else if (rc == SQLITE_DONE)
        {
            printf("未找到记录: %s\n", timestamp);
        }
        else
        {
            fprintf(stderr, "SQL查询错误: %s\n", sqlite3_errmsg(db));
        }

        sqlite3_finalize(stmt);
    }
    else
    {
        fprintf(stderr, "SQL准备失败: %s\n", sqlite3_errmsg(db));
    }

    return result;
}

// 获取最新时间戳
char *get_latest_timestamp()
{
    sqlite3_stmt *stmt;
    const char *sql = "SELECT MAX(timestamp) FROM data_records";
    char *ts = NULL;

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK)
    {
        int rc = sqlite3_step(stmt);
        if (rc == SQLITE_ROW)
        {
            const unsigned char *tmp = sqlite3_column_text(stmt, 0);
            if (tmp)
            {
                ts = strdup((char *)tmp);
                printf("获取最新时间戳: %s\n", ts);
            }
            else
            {
                printf("最新时间戳为空\n");
            }
        }
        else if (rc == SQLITE_DONE)
        {
            printf("数据库为空\n");
        }
        else
        {
            fprintf(stderr, "SQL查询错误: %s\n", sqlite3_errmsg(db));
        }

        sqlite3_finalize(stmt);
    }
    else
    {
        fprintf(stderr, "SQL准备失败: %s\n", sqlite3_errmsg(db));
    }

    return ts;
}

// 创建查询响应的JSON
char *create_query_response_json(QueryResponse *resp)
{
    printf("创建响应: action=%s, timestamp=%s, error_code=%d\n",
           resp->action, resp->timestamp, resp->error_code);

    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "action", resp->action);
    cJSON_AddStringToObject(root, "timestamp", resp->timestamp);

    if (resp->error_code == 0)
    {
        if (strcmp(resp->action, "get_data") == 0)
        {
            // 解析data字段中的JSON字符串
            cJSON *data_obj = cJSON_Parse(resp->data);
            if (data_obj)
            {
                cJSON_AddItemToObject(root, "data", data_obj); // 直接添加解析后的对象
            }
            else
            {
                // 解析失败时添加错误信息
                cJSON_AddStringToObject(root, "data", "parse_error");
                printf("JSON解析失败: %s\n", resp->data);
            }
        }
        cJSON_AddNumberToObject(root, "error_code", 0);
    }
    else
    {
        cJSON_AddNumberToObject(root, "error_code", resp->error_code);
        cJSON_AddStringToObject(root, "error_msg", resp->error_msg);
    }

    char *json = cJSON_Print(root);
    cJSON_Delete(root);
    return json;
}

// 发布MQTT消息
void publish_mqtt_message(char *topic, char *payload)
{
    if (!topic || !payload)
    {
        printf("发布MQTT消息失败: 主题或载荷为空\n");
        return;
    }

    printf("发布MQTT消息到主题: %s\n", topic);

    MQTTClient_message msg = MQTTClient_message_initializer;
    msg.payload = payload;
    msg.payloadlen = strlen(payload);
    msg.qos = QOS;
    msg.retained = 0;

    MQTTClient_deliveryToken token;
    if (MQTTClient_publishMessage(client, topic, &msg, &token) == MQTTCLIENT_SUCCESS)
    {
        MQTTClient_waitForCompletion(client, token, TIMEOUT);
        printf("MQTT消息发布成功\n");
    }
    else
    {
        fprintf(stderr, "MQTT发布失败\n");
    }
}

// 处理SQLite查询请求
void handle_sqlite_query()
{
    if (sqlite_query_flag == 0)
    {
        return;
    }

    printf("处理SQLite查询请求: flag=%d\n", sqlite_query_flag);

    QueryResponse resp = {0};

    sem_wait(shm_sem);
    printf("获取信号量，处理查询: flag=%d, timestamp=%s\n",
           sqlite_query_flag, sqlite_timestamp ? sqlite_timestamp : "NULL");

    if (sqlite_query_flag == 1)
    {
        // 查询最新时间戳
        char *latest_ts = get_latest_timestamp();
        if (latest_ts)
        {
            strcpy(resp.action, "get_timestamp");
            strcpy(resp.timestamp, latest_ts);
            resp.error_code = 0;
            free(latest_ts);
            printf("最新时间戳查询成功: %s\n", resp.timestamp);
        }
        else
        {
            strcpy(resp.action, "get_timestamp");
            resp.error_code = 1;
            strcpy(resp.error_msg, "no_records");
            printf("最新时间戳查询失败: 无记录\n");
        }
    }
    else if (sqlite_query_flag == 2 && sqlite_timestamp)
    {
        // 查询指定时间戳数据
        char *data = query_data_by_timestamp(sqlite_timestamp);
        if (data)
        {
            strcpy(resp.action, "get_data");
            strcpy(resp.timestamp, sqlite_timestamp);

            // 确保不超过缓冲区大小
            size_t data_len = strlen(data);
            if (data_len < sizeof(resp.data))
            {
                strcpy(resp.data, data);
            }
            else
            {
                strncpy(resp.data, data, sizeof(resp.data) - 1);
                resp.data[sizeof(resp.data) - 1] = '\0';
                printf("警告: 数据截断，原始长度: %zu, 缓冲区大小: %zu\n",
                       data_len, sizeof(resp.data));
            }

            resp.error_code = 0;
            free(data);
            printf("数据查询成功: %s\n", resp.timestamp);
        }
        else
        {
            strcpy(resp.action, "get_data");
            strcpy(resp.timestamp, sqlite_timestamp);
            resp.error_code = 2;
            strcpy(resp.error_msg, "data_not_found");
            printf("数据查询失败: 未找到记录 %s\n", resp.timestamp);
        }
    }
    else
    {
        printf("无效的查询标志: %d\n", sqlite_query_flag);
    }

    printf("查询处理完成，释放信号量\n");
    sem_post(shm_sem);

    // 转换为JSON格式
    char *json_resp = create_query_response_json(&resp);
    if (json_resp)
    {
        // 发布到MQTT
        publish_mqtt_message(TOPIC_UP, json_resp);
        free(json_resp);
    }
    else
    {
        printf("JSON响应创建失败\n");
    }

    // 重置查询标志
    sem_wait(shm_sem);
    sqlite_query_flag = 0;
    if (sqlite_timestamp)
    {
        free(sqlite_timestamp);
        sqlite_timestamp = NULL;
    }
    printf("SQLite查询标志已重置\n");
    sem_post(shm_sem);
}

// 主函数
int main()
{
    signal(SIGINT, sig_handler);
    signal(SIGTERM, sig_handler);

    // 初始化共享内存
    if (shm_init(&shm, SHARED_MEM_NAME, sizeof(ConfigData), 0) != 0)
    {
        fprintf(stderr, "共享内存初始化失败\n");
        return 1;
    }

    ConfigData *config = (ConfigData *)shm_getaddr(&shm);
    if (!config)
    {
        fprintf(stderr, "获取共享内存地址失败\n");
        shm_detach(&shm);
        return 1;
    }

    // 初始化信号量
    shm_sem = sem_open(SEM_NAME, 0);
    if (shm_sem == SEM_FAILED)
    {
        perror("打开信号量失败");
        shm_detach(&shm);
        return 1;
    }

    // 初始化数据库
    if (init_database() != 0)
    {
        fprintf(stderr, "数据库初始化失败\n");
        sem_close(shm_sem);
        shm_detach(&shm);
        return 1;
    }

    // 启动数据库采集线程
    if (pthread_create(&sqlite_thread, NULL, database_thread_func, config) != 0)
    {
        fprintf(stderr, "创建数据库线程失败\n");
        sqlite3_close(db);
        sem_close(shm_sem);
        shm_detach(&shm);
        return 1;
    }

    // 初始化MQTT连接
    if (mqtt_init() != 0)
    {
        fprintf(stderr, "MQTT初始化失败\n");
        pthread_cancel(sqlite_thread);
        sqlite3_close(db);
        sem_close(shm_sem);
        shm_detach(&shm);
        return 1;
    }

    printf("系统启动成功，上报类型: %d ,周期: %d秒\n",
           config->report.type, config->report.period);

    time_t last_publish = time(NULL);

    // 主循环
    while (running)
    {
        // 根据上报类型处理数据上报
        switch (config->report.type)
        {
        case 1: // 定时上报
            if (time(NULL) - last_publish >= config->report.period)
            {
                publish_data(config);
                copy_config(config, &last_config);
                last_publish = time(NULL);
            }
            break;

        case 2: // 变化上报
            if (first_run || has_config_changed(config, &last_config))
            {
                publish_data(config);
                copy_config(config, &last_config);
                first_run = 0;
            }
            break;

        case 3: // 刷新上报
            if (first_run || remote_refresh)
            {
                publish_data(config);
                copy_config(config, &last_config);
                first_run = 0;
                remote_refresh = 0;
            }
            break;
        }
        // 处理SQLite查询请求
        handle_sqlite_query();

        // 短暂休眠避免CPU占用过高
        usleep(100000); // 100ms
    }

    // 清理资源
    pthread_join(sqlite_thread, NULL);
    sqlite3_close(db);
    MQTTClient_disconnect(client, 1000);
    MQTTClient_destroy(&client);
    sem_close(shm_sem);
    shm_detach(&shm);

    return 0;
}
